package scutiger.util;

/**
 * @author LEI
 * Created by LEI on 2020/6/18.
 */
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.yaml.snakeyaml.Yaml;

public class YmlUtil {

    private static final String yml = "scutiger.yml";
    private static Map map = new HashMap();
    public static final boolean log = true;

    public static Object getYml(String path) {
        Yaml yaml = new Yaml();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        URL url = classLoader.getResource(yml);
        if (url != null) {
            try {
                if(map.size() <=0){
                    map = (Map) yaml.load(new FileInputStream(url.getFile()));
                }
                return getValue(map, path);
            } catch (FileNotFoundException e) {
                System.out.println("请配置你的yml文件");
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }

    @SuppressWarnings("rawtypes")
    public static Object getValue(Map map, String value) {
        String[] values = value.split("\\.");
        Map m = map;
        int len = values.length - 1;
        for (int i = 0; i < len; i++) {
            if (m.containsKey(values[i])) {
                m = (Map) m.get(values[i]);
            } else {
                return null;
            }
        }
        return m.get(values[len]);
    }

}
